package com.longge;

/**
 * @program: my-code
 * @description:
 * @author: longge
 * @create: 2021-04-20 01:20
 */
public class ReorderList {
    Boolean status = false;

    public void reorderList(ListNode head) {
        ListNode slow = head, fast = head, cur = head;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        if (slow==fast) return;
        ListNode right = reserve(cur, slow);
        slow.next = null;
        ListNode dum = new ListNode(0);
        while (right != null) {
            dum.next = head;
            head = head.next;
            dum.next.next = right;
            right = right.next;
            dum = dum.next.next;
        }
        if (head!=null){
            dum.next = head;
        }
    }

    private ListNode reserve(ListNode cur, ListNode slow) {
        if (cur.next == null) return cur;
        ListNode head = reserve(cur.next, slow);
        if (cur == slow || status) {
            status = true;
            return head;
        }
        cur.next.next = cur;
        cur.next = null;
        return head;
    }

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        node1.next = node2;
        node2.next = node3;
        node3.next=node4;
        new ReorderList().reorderList(node1);
    }
}
